<template>
  <div class="main">
    <div class="air-column">
      <h2>乘机人</h2>
      <el-form class="member-info" :model="{users}" ref="userForm">
        <div class="member-info-item" v-for="(user,index) in users" :key="index">
          <el-form-item
            label="乘机人类型"
            :prop="`users[${index}].username`"
            :rules="[
          { required: true, message: '请输入乘机人', trigger: 'blur' }
          ]"
          >
            <el-input placeholder="姓名" class="input-with-select" v-model="user.username">
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="成人" value="1"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <el-form-item
            label="证件类型"
            :prop="`users[${index}].id`"
            :rules="[
          { required: true, message: '请输入证件号码', trigger: 'blur' },
          {pattern:/^\d{18}$/,message:'不符合身份证格式',trigger: 'blur'}
          ]"
          >
            <el-input placeholder="证件号码" class="input-with-select" v-model="user.id">
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="身份证" value="1" :checked="true"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers">添加乘机人</el-button>
    </div>
    <div class="air-column">
      <h2>保险</h2>
      <div>
        <!-- <div class="insurance-item">
          <el-checkbox label="航空意外险：￥30/份×1  最高赔付260万" border></el-checkbox>
        </div>-->
        <el-checkbox-group v-model="insurances" class="insurance-list">
          <el-checkbox
            class="insurance-item"
            v-for="(item,index) in data.insurances"
            :key="index"
            :label="item.id"
          >{{`${item.type}：￥${item.price}/份×${users.length} 最高赔付${item.compensation}`}}</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          class="contactForm"
          label-width="80px"
          :model="{
            contactName,
      contactPhone,
      captcha
        }"
          :rules="contactRules"
          ref="contactForm"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="contactName"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input placeholder="请输手机号" v-model="contactPhone">
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="captcha"></el-input>
          </el-form-item>
        </el-form>
        <el-button
          v-if="$store.state.user.username.token"
          type="warning"
          class="submit"
          @click="handleSubmit"
        >提交订单</el-button>

        <el-row v-else type="flex" justify="center" align="middle" class="loginForm">
          <div class="form-wrapper">
            <!-- 表单头部tab -->
            <el-row type="flex" justify="center" class="tabs">
              <span
                :class="{active: currentTab === index}"
                v-for="(item, index) in [`登录`, `注册`]"
                :key="index"
                @click="currentTab=index"
              >{{item}}</span>
            </el-row>

            <!-- 登录功能组件 -->
            <LoginForm v-if="currentTab == 0" />

            <!-- 注册功能组件 -->
            <RegisterForm @tologin="currentTab=0" v-if="currentTab == 1" />
          </div>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import LoginForm from "@/components/user/LoginForm";
import RegisterForm from "@/components/user/RegisterForm";
export default {
  components: {
    LoginForm,
    RegisterForm
  },
  props: {
    data: Object
  },
  data() {
    return {
      currentTab: 0,
      //   user: {
      //     username: "",
      //     id: ""
      //   },
      users: [
        //这个数组负责管理乘机人,
        {
          username: "",
          id: ""
        }
      ],
      insurances: [],
      contactName: "",
      contactPhone: "",
      captcha: "",
      contactRules: {
        contactName: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "请输入电话", trigger: "blur" }
        ],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      }
    };
  },
  watch: {
    // users() {
    //   console.log("乘机人发生了变化");
    //   this.calcTotalPrice();
    // },
    // insurances() {
    //   console.log("保险发生了变化");
    //   this.calcTotalPrice();
    // }
    users: {
      handler() {
        // console.log("乘机人发生了变化");
        this.$emit("num", this.users.length);
        this.calcTotalPrice();
      },
      immediate: true
    },
    insurances: {
      handler() {
        // console.log("保险发生了变化");
        this.calcTotalPrice();
      },
      immediate: true
    }
  },
  methods: {
    calcTotalPrice() {
      //机票价格
      let res = 0;
      res += this.data.seat_infos.org_settle_price * this.users.length;
      // console.log(res);
      //保险价格
      this.data.insurances.forEach(e => {
        //代表保险被选中
        if (this.insurances.indexOf(e.id) >= 0) {
          res += e.price * this.users.length;
        }
      });
      // console.log(res);
      //兄弟组件传值需要通过子组件
      this.$emit("setTotalPrice", res);
    },
    // 添加乘机人
    handleAddUsers() {
      this.users.push({
        username: "",
        id: ""
      });
    },

    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },

    // 发送手机验证码
    handleSendCaptcha() {
      this.$axios({
        url: "/captchas",
        method: "POST",
        data: {
          tel: this.contactPhone
        }
      }).then(res => {
        console.log(res.data);
        this.$message.success("验证码发送成功:" + res.data.code);
      });
    },

    // 提交订单
    async handleSubmit() {
      let userValid = await this.$refs.userForm.validate().catch(err => {});
      console.log(userValid);

      let contactValid = await this.$refs.contactForm
        .validate()
        .catch(err => {});
      console.log(contactValid);
      if (userValid && contactValid) {
        // console.log(this.users);
        // console.log(this.insurances);
        //接口文档有错,少个captcha参数
        const data = {
          users: this.users,
          insurances: this.insurances,
          contactName: this.contactName,
          contactPhone: this.contactPhone,
          invoice: true,
          seat_xid: this.$route.query.seat_xid,
          air: this.$route.query.id,
          captcha: this.captcha
        };
        this.$axios({
          url: "/airorders",
          method: "POST",
          data,
          headers: {
            // Authorization: this.$store.state.user.username.token,
            // jwt格式 Bearer持有者，注意引号后面一定要有一个空格
            Authorization: "Bearer " + this.$store.state.user.username.token
          }
        }).then(res => {
          console.log(res.data);
          this.$router.push({
            path: "/air/pay",
            query: {
              id: res.data.data.id
            }
          });
        });
      }
    }
  },
  mounted() {
    //进入页面先计算一次
    // this.calcTotalPrice();
  }
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 0;
  .el-form-item__error {
    padding-left: 134px;
  }
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance-list {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.insurance-item {
  margin-bottom: 20px;
  border: 1px solid #e4e4e4;
  padding: 10px;
}

.contact {
  .contactForm {
    /deep/ .el-input {
      width: 50%;
    }
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
.loginForm {
  height: 100%;
  margin: 0 auto;
  position: relative;

  .form-wrapper {
    width: 400px;
    margin: 0 auto;
    background: #fff;
    box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .tabs {
      span {
        display: block;
        width: 50%;
        height: 50px;
        box-sizing: border-box;
        border-top: 2px #eee solid;
        background: #eee;
        line-height: 48px;
        text-align: center;
        cursor: pointer;
        color: #666;

        &.active {
          color: orange;
          border-top-color: orange;
          background: #fff;
          font-weight: bold;
        }
      }
    }
  }
}
</style>